package com.ruiysoft.controller.cart;

import com.ruiysoft.controller.anchor.Anchor;
import com.ruiysoft.controller.anchor.AnchorEnum;
import com.ruiysoft.controller.cart.vo.CartListVo;
import com.ruiysoft.controller.mdse.InnrApi;
import com.ruiysoft.controller.mdse.vo.SkuListVo;
import com.ruiysoft.entity.sys.SysMicroShop;
import com.ruiysoft.entity.sys.SysShopPersonnel;
import com.ruiysoft.pub.core.Result;
import com.ruiysoft.pub.core.ResultGenerator;
import com.ruiysoft.service.cart.ICartService;
import com.ruiysoft.service.sys.clent.LoginContextUtil;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2018-11-06T20:50:21.840+08:00")

@RestController
public class CartApiController implements CartApi {

    private static final Logger log = LoggerFactory.getLogger(CartApiController.class);

    private final ICartService cartService;


    @Resource
    private InnrApi innrApi;

    @org.springframework.beans.factory.annotation.Autowired
    public CartApiController(ICartService cartService) {
        this.cartService = cartService;
    }

    private Long getUserId() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        if (null == personnel){
            return null;
        }
        return personnel.getId();
    }
    private SysShopPersonnel getUser() {
        SysShopPersonnel personnel = LoginContextUtil.instance().getEntryUser().getPersonnel();
        if (null == personnel){
            return null;
        }
        return personnel;
    }
    private Long getShopId() {
        SysMicroShop shop = LoginContextUtil.instance().getEntryMicroShop();
        return shop.getId();
    }

    @Override
    @Anchor(anchorType = AnchorEnum.SHOPCART,skuId = "#skuId")
    public Result<Void> cartAddSkuIdNumPost(@ApiParam(value = "",required=true) @PathVariable("skuId") Long skuId, @ApiParam(value = "",required=true) @PathVariable("num") Integer num) {
        Long shopId = getShopId();
        Long userId = getUserId();
        try {
            cartService.addSkuIdNum(shopId,userId,skuId,num);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("购物车添加商品--{}--{}--{}--{}",shopId,userId,skuId,num ,e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Void> cartDelSkuIdPost(@ApiParam(value = "",required=true) @PathVariable("skuId") Long skuId) {
        Long shopId = getShopId();
        Long userId = getUserId();
        try {
            cartService.delSkuId(shopId,userId,skuId);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("购物车删除商品--{}--{}--{}",shopId,userId,skuId ,e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<List<CartListVo>> cartListGet() {
        Long shopId = getShopId();
        Integer mLv = null;
        SysShopPersonnel personnel = getUser();
        Long userId = personnel.getId();
        try{
            if(Optional.ofNullable(personnel.getMemberFlag()).orElse(false)){
                mLv = personnel.getMemberLevel();
            }
        }catch (Exception e){
            log.error("购物车列表cartListGet，获取会员信息--{}--{}",shopId,userId ,e);
        }
        try {
            LinkedHashMap<Long,Long> cartMap = cartService.cartList(shopId,userId);
            if(cartMap.isEmpty()){
                return ResultGenerator.genSuccessResult();
            }
            Result<Map<Long,SkuListVo>> result = innrApi.innrMdseSkuListCartPost(cartMap.keySet().stream().collect(Collectors.toList()),mLv);
            if(result.isSuccess()){
                return ResultGenerator.genSuccessResult(cartMap.entrySet().stream()
                        .map(entry->new CartListVo()
                                .num(entry.getValue().intValue())
                                .skuId(entry.getKey())
                                .sku(result.getData().get(entry.getKey())))
                        .filter(cart->cart.getSku()!=null)
                        .collect(Collectors.toList()));
            }else{
                log.error("购物车列表cartListGet,查询商品失败--{}--{}",shopId,userId);
                return ResultGenerator.genSuccessResult();
            }
        } catch (Exception e) {
            log.error("购物车列表cartListGet--{}--{}",shopId,userId ,e);
            return ResultGenerator.genFailResult(e.getMessage());
        }

    }

    @Override
    public Result<Void> cartSubtractSkuIdNumPost(@ApiParam(value = "",required=true) @PathVariable("skuId") Long skuId, @ApiParam(value = "",required=true) @PathVariable("num") Integer num) {
        Long shopId = getShopId();
        Long userId = getUserId();
        try {
            cartService.subtractSkuIdNum(shopId,userId,skuId,num);
            return ResultGenerator.genSuccessResult();
        } catch (Exception e) {
            log.error("购物车减少商品--{}--{}--{}--{}",shopId,userId,skuId,num ,e);
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @Override
    public Result<Integer> cartSumGet() {
        Long shopId = getShopId();
        Long userId = getUserId();
        try {
            return ResultGenerator.genSuccessResult(cartService.cartSum(shopId,userId));
        } catch (Exception e) {
            log.error("购物车获取数量cartSumGet--{}--{}",shopId,userId ,e);
            return ResultGenerator.genFailResult(e.getMessage());
        }

    }

}
